//
//  MSPopupManager.m
//  MSPopupsManager
//
//  Created by zz on 22.4.24.
//

#import "MSPopupManager.h"
#import "MSPopupEntity.h"

@interface MSPopupManager()

@property (nonatomic, strong) NSMutableArray<MSPopupEntity *> *windowQueue;

@end

@implementation MSPopupManager

+ (instancetype)defaultManager {
    static dispatch_once_t onceToken;
    static MSPopupManager *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}


+ (id)allocWithZone:(struct _NSZone *)zone {
    return [self defaultManager];
}

#pragma mark 添加方法
+ (void)addPopup:(id<MSPopupProtocol>)popup options:(MSPopupConfigure *)options{
    MSPopupManager *manage = [MSPopupManager defaultManager];
    [manage addPopup:popup priority:0 options:options];
}

- (void)addPopup:(id<MSPopupProtocol>)popup priority:(NSInteger)priority options:(MSPopupConfigure *)options {
    
    //弹窗配置对象
    MSPopupConfigure *config = [MSPopupConfigure new];
    config = options;
    [config configureDefaultParams];
    
    config.containerView = config.containerView ? config.containerView : [UIApplication sharedApplication].keyWindow;
    //    config.containerView = [UIApplication sharedApplication].keyWindow;
    
    CGRect popupFrame = config.containerView.bounds;
    
    //弹窗数据模型
    MSPopupEntity *model = [[MSPopupEntity alloc] init];
    model.config = config;
    model.popupObj = popup;
    MSPopupBackgroundView *bgView = [[MSPopupBackgroundView alloc] initWithFrame:popupFrame];
    bgView.backgroundColor = config.backgroundColor;
    model.popupBgView = bgView;
    
    if (![popup conformsToProtocol:@protocol(MSPopupProtocol)]) {
        return;
    }
    
    //将弹窗内容视图添加到弹窗背景视图中
    [model.popupBgView addSubview:[popup supportAtmospherePopupView]];
    [model addGestureRecognizer];
    
    //pop
    [self popWithModel:model isRecover:NO];
}

- (void)popWithModel:(MSPopupEntity *)model isRecover:(BOOL)isRecover {
    /// circuitBreaker模式只会把相同的Group下的弹窗移除
    if (model.config.circuitBreaker) {
        NSArray * stackSource = [self getStackPopupsList];
        if (stackSource.count > 0) {
            NSMutableArray *waitRemoveArr = [[NSMutableArray alloc] initWithArray:stackSource];
            while (waitRemoveArr.count) {
                [self dismissWithModel:waitRemoveArr.lastObject];
                [waitRemoveArr removeLastObject];
            }
        }
    }
    // 默认展示图层
    [self popTopPopupsWithModel:model];
    
    MSPopupEntity * lastEntiy = [self getPopupsStackTopAlertView];
    if (lastEntiy) {
        //如果新进来的弹窗优先级比当前展示的弹窗优先级高
        if (model.config.priority >= lastEntiy.config.priority) {
            [lastEntiy.popupBgView endEditing:YES];
            //当前组展示的弹窗被优先级高的顶替掉了
            [self dismissOtherTopPopupsWithModel:lastEntiy];
        } else {
            //先入列排队等待展示
            [self enterPopWindsQueueWithModel:model];
            return;
        }
    }
    
    if (!model.popupBgView.superview) {
        [model.config.containerView addSubview:model.popupBgView];
        [model.config.containerView bringSubviewToFront:model.popupBgView];
    }
    
    //弹窗内容自定义布局
    if ([model.popupObj respondsToSelector:@selector(layoutContentWithSuperView:)]) {
        [model.popupObj layoutContentWithSuperView:model.popupBgView];
    }
    //获取到业务中ContentView的frame
    [model.popupBgView layoutIfNeeded];
    //缓存弹窗内容的原始frame
    //model.originalFrame = [model.popupObj supplyCustomPopupView].frame;
    
    //开启定时器
    if (model.config.dismissDuration >= 1) {
        [model startCountTime];
    }
    //入列
    if (!isRecover) {
        [self enterPopWindsQueueWithModel:model];
    }
    //配置圆角
    [model setupCustomViewCorners];
    
    model.config.popViewDidShowCallback ? model.config.popViewDidShowCallback() : nil;
    
    if ([model.popupObj respondsToSelector:@selector(popupViewDidAppear)]) {
        [model.popupObj popupViewDidAppear];
    }
}


- (MSPopupEntity *)getPopupsStackTopAlertView {
    if (self.windowQueue.count > 0) {
        return  self.windowQueue.lastObject;
    }
    return nil;
}


//进入队列的元素都要进行优先级排序，优先级最高的放到数组的末尾
- (void)enterPopWindsQueueWithModel:(MSPopupEntity *)model {
    for (MSPopupEntity *item in self.windowQueue) {
        if (item == model) {
            return;
        }
    }
    [self.windowQueue addObject:model];
    if (self.windowQueue.count < 2) {
        return;
    }
    //插入排序进行优先级调整
    MSPopupEntity *lastModel = self.windowQueue.lastObject;
    NSInteger i = self.windowQueue.count - 1;
    NSInteger j = i-1;
    while (j >= 0&& self.windowQueue[j].config.priority > lastModel.config.priority) {
        [self.windowQueue replaceObjectAtIndex:j+1 withObject:self.windowQueue[j]];
        j--;
    }
    self.windowQueue[j+1] = lastModel;
}


#pragma mark - Dismiss
- (MSPopupEntity *)getModelWithPopup:(id<MSPopupProtocol>)popup {
    if (!popup) {  return nil; }
    for (MSPopupEntity *itemModel in self.windowQueue) {
        if (itemModel.popupObj == popup) {
            return itemModel;
        }
    }
    return nil;
}


/// 筛选出给定弹窗数组中弹窗模型
/// - Parameter popupList: popupList description
- (NSArray *)getStackPopupsList {
    if (self.windowQueue.count < 1) {
        return nil;
    }
    NSMutableArray *resultArr = [[NSMutableArray alloc] init];
    for (MSPopupEntity *itemModel in self.windowQueue) {
        [resultArr addObject:itemModel];
    }
    return [resultArr copy];
}

+ (void)dismissWithPopup:(id<MSPopupProtocol>)popup {
    MSPopupEntity *model = [[MSPopupManager defaultManager] getModelWithPopup:popup];
    if (model) {
        [[MSPopupManager defaultManager] dismissWithModel:model];
    }
}


- (NSInteger)getTopPopupsCount {
    return self.windowQueue.count;
}

/// 隐藏最上层以外的Entity
/// - Parameter model: model description
- (void)dismissOtherTopPopupsWithModel:(MSPopupEntity *)model {
    if (model.config.dismissDuration > 0) {
        [model closeTimer];
    }
    
    [UIView animateWithDuration:0.25 animations:^{
        model.popupBgView.backgroundColor = [self drawBackgroundViewColorWith:model.config.backgroundColor
                                                                        alpha:model.config.backgroundAlpha
                                                                    withModel:model];
        //        [model contentView].alpha = 0.0f;
        model.popupBgView.alpha = 0.0f;
    }];
}

/// 显示最上层以外的Entity
/// - Parameter model: model description
- (void)popTopPopupsWithModel:(MSPopupEntity *)model {
    //背景动画执行
    model.popupBgView.backgroundColor = [self drawBackgroundViewColorWith:model.config.backgroundColor
                                                                    alpha:model.config.backgroundAlpha
                                                                withModel:model];
    //    [model contentView].alpha = 1.0f;
    model.popupBgView.alpha = 1.0f;
}


- (UIColor *)drawBackgroundViewColorWith:(UIColor *)color alpha:(CGFloat)alpha withModel:(MSPopupEntity *)model {
    if (model.popupBgView.isHiddenBg) {
        return UIColor.clearColor;
    }
    if (model.config.backgroundColor == UIColor.clearColor) {
        return UIColor.clearColor;
    }
    CGFloat red = 0.0;
    CGFloat green = 0.0;
    CGFloat blue = 0.0;
    CGFloat resAlpha = 0.0;
    [color getRed:&red green:&green blue:&blue alpha:&resAlpha];
    UIColor *resColor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    return resColor;
}


- (void)dismissWithModel:(MSPopupEntity *)model {
    //存放入待移除的队列中
    /**
     1:删除当前正在展示的entity
     */
    [self divertToWaitRemoveQueueWithModel:model];
    
    
    NSInteger stackCount = [self getTopPopupsCount];
    if (stackCount >= 1) {
        //如果当前移除的弹窗之前还有被覆盖的，则把之前的重新展示出来
        MSPopupEntity * lastEntity = [self getPopupsStackTopAlertView];
        //开启定时器
        if (lastEntity.config.dismissDuration >= 1) {
            [lastEntity startCountTime];
        }
        /**
         这里需要延迟执行？时间为push的动画
         */
        [self popTopPopupsWithModel:lastEntity];
    }
    
    //将要关闭
    model.config.popViewDidDismissCallback ? model.config.popViewDidDismissCallback() : nil;
    if ([model.popupObj respondsToSelector:@selector(popupViewDidDisappear)]) {
        [model.popupObj popupViewDidDisappear];
    }
    
    // 移除上一个展示UIView的计时器
    [model closeTimer];
    [model.popupBgView removeFromSuperview];
}

//将需要移除的弹窗转移到另外一个队列
- (void)divertToWaitRemoveQueueWithModel:(MSPopupEntity *)model {
    NSArray *allArr = [self getAllPopViewFromContainerView:model.config.containerView];
    [allArr enumerateObjectsUsingBlock:^(MSPopupEntity *obj, NSUInteger idx, BOOL * stop) {
        if ([obj.popupObj isEqual:model.popupObj]) {
            //            [self.waitRemovePool addObject:model];
            [self.windowQueue removeObject:model];
        }
    }];
}

+ (void)clearWindowQueue {
    MSPopupManager *manage = [MSPopupManager defaultManager];
    [manage.windowQueue removeAllObjects];
}

+ (void)clear {
    NSArray * stackSource = [MSPopupManager.defaultManager getStackPopupsList];
    if (stackSource.count > 0) {
        NSMutableArray *waitRemoveArr = [[NSMutableArray alloc] initWithArray:stackSource];
        while (waitRemoveArr.count) {
            [MSPopupManager.defaultManager dismissWithModel:waitRemoveArr.lastObject];
            [waitRemoveArr removeLastObject];
        }
    }
}

//获取同一个容器中的所有未移除的弹窗（包含所有Group）
- (NSArray *)getAllPopViewFromContainerView:(UIView *)containerView {
    NSMutableArray *fromArr = self.windowQueue;
    NSMutableArray *toArr = [NSMutableArray array];
    for (MSPopupEntity *item in fromArr) {
        if ([item.config.containerView isEqual:containerView]) {
            [toArr addObject:item];
        }
    }
    return [NSArray arrayWithArray:toArr];
}



- (NSMutableArray<MSPopupEntity *> *)windowQueue {
    if (!_windowQueue) {
        _windowQueue = [[NSMutableArray alloc] init];
    }
    return _windowQueue;
}

@end
